package com.woniuxy.ticketgateway;

import com.woniuxy.commnes.entity.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName AuthFilter
 * @Description 全局过滤器
 * @Author zx
 * @Date 2021-03-04 16:42:25
 * @Version 1.0
 */
@Slf4j
//@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Resource
    private AuthService authService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.debug("AuthFilter");
        String url= exchange.getRequest().getURI().getPath();
        String jwt = exchange.getRequest().getHeaders().getFirst("jwt");
//        exchange.getRequest().
        ResponseResult<Void> result = authService.parseJwt(jwt,url);
        if (result.getCode()==403){
            return  authErro(exchange.getResponse(),"无权限");
        }else if (result.getCode()==405){
            return  authErro(exchange.getResponse(),"无登录");
        }
        return chain.filter(exchange);
    }
    private Mono<Void> authErro(ServerHttpResponse resp, String mess) {
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        resp.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        DataBuffer buffer = resp.bufferFactory().wrap("error".getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
